// TODO: remove this when you're done with your implementation.
#![allow(unused_variables, dead_code)]

//https://google.github.io/comprehensive-rust/zh-CN/exercises/day-1/luhn.html
pub fn luhn(cc_number: &str) -> bool {
    let mut digits_seen = 0;
    let mut sum = 0;
    for (i, ch) in cc_number.chars().rev().filter(|&ch| ch != ' ').enumerate() {
        // println!("{} {}", i, ch);
        match ch.to_digit(10) {
            Some(d) => {
                sum += if i % 2 == 1 {
                    //如果是奇数位，则*2
                    // 这里的i 实际是从0开始计算，则余数为1表示偶数位的元素
                    let dd = d * 2;
                    dd / 10 + dd % 10
                } else {
                    d //基数位的元素直接叠加给sum
                };
                digits_seen += 1;
            }
            None => return false,
        }
    }
    if digits_seen < 2 {
        return false;
    }
    //判断结果是否以0结尾
    // println!("sum {}", sum);
    sum % 10 == 0
}

#[test]
fn test_non_digit_cc_number() {
    assert!(!luhn("foo"));
    assert!(!luhn("foo 0 0"));
}

#[test]
fn test_empty_cc_number() {
    assert!(!luhn(""));
    assert!(!luhn(" "));
    assert!(!luhn("  "));
    assert!(!luhn("    "));
}

#[test]
fn test_single_digit_cc_number() {
    assert!(!luhn("0"));
}

#[test]
fn test_two_digit_cc_number() {
    assert!(luhn(" 0 0 "));
}

#[test]
fn test_valid_cc_number() {
    assert!(luhn("4263 9826 4026 9299"));
    assert!(luhn("4539 3195 0343 6467"));
    assert!(luhn("7992 7398 713"));
}

#[test]
fn test_invalid_cc_number() {
    assert!(!luhn("4223 9826 4026 9299"));
    assert!(!luhn("4539 3195 0343 6476"));
    assert!(!luhn("8273 1232 7352 0569"));
}

#[allow(dead_code)]
fn main() {}
